package bind

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mon-go-web/pkg/logger"
	"mon-go-web/pkg/response"
	"net/http"
)

func Json[T any](c *gin.Context, obj *T, handler func(*gin.Context, *T)) {
	if err := c.ShouldBindJSON(obj); err != nil {
		logger.Logger.Error("Failed to bind JSON in route", zap.Error(err))
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	handler(c, obj)
}

func Query[T any](c *gin.Context, obj *T, handler func(*gin.Context, *T)) {
	if err := c.ShouldBindQuery(obj); err != nil {
		logger.Logger.Error("Failed to bind query parameters in route", zap.Error(err))
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	handler(c, obj)
}

func Post[T any](group *gin.RouterGroup, path string, handler func(*gin.Context, *T)) {
	group.POST(path, func(c *gin.Context) {
		var obj T
		Json(c, &obj, handler)
	})
}

func Get[T any](group *gin.RouterGroup, path string, handler func(*gin.Context, *T)) {
	group.GET(path, func(c *gin.Context) {
		var obj T
		Query(c, &obj, handler)
	})
}
